package org.footballmanager.pandafootball.common.intercepter;

import org.footballmanager.pandafootball.common.constants.Constants;
import org.footballmanager.pandafootball.common.util.MakeCookie;
import org.footballmanager.pandafootball.system.domain.*;
import org.footballmanager.pandafootball.system.form.impl.FootZnxSearchForm;
import org.footballmanager.pandafootball.system.service.*;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 自定义拦截器
 *
 * @author  chenjian
 * @since	2016年1月7日
 */
public class MyInterceptor extends HandlerInterceptorAdapter {
    private FootZnxService footZnxService;
    private FootTeamService footTeamService;
    private FootSjService footSjService;
    private FootMissionService footMissionService;
    private FootBfinfoService footBfinfoService;
    private FootSociatyInfoService footSociatyInfoService;

	/**
	 * 之前拦截
	 * @param request 参数
	 * @param response 参数
	 * @param handler 参数
	 * @return 返回值
	 * @throws Exception 异常
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//System.out.println(">>>MyInterceptor>>>>>>>在请求处理之前进行调用（Controller方法调用之前）" + request.getRequestURL())
		// 只有返回true才会继续向下执行，返回false取消当前请求
        HttpSession session = request.getSession(true);
        FootUser user = (FootUser)session.getAttribute(Constants.USER);
        boolean flag = true;
        if(user == null && !MakeCookie.isToday((Date)request.getSession().getAttribute("nowTime"), new Date())){
           response.sendRedirect("/login");
           flag = false;
        }
		return flag;
	}

	/**
	 * 之后拦截
	 * @param request 参数
	 * @param response 参数
	 * @param handler 参数
	 * @param modelAndView 参数
	 * @throws Exception 异常
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        processService(request);
		processData(request);

	}

	/**
	 * 处理服务
	 * @param request 参数
	 */
	private void processService(HttpServletRequest request) {
		ServletContext sc = request.getSession().getServletContext();
		WebApplicationContext cxt = WebApplicationContextUtils.getWebApplicationContext(sc);
		String znxServiceStr = "footZnxService";
		String teamServiceStr = "footTeamService";
		String sjServiceStr = "footSjService";
        String missionServiceStr = "footMissionService";
        String bfServiceStr = "footBfinfoService";
        String sociatyServiceStr = "footSociatyInfoService";
		if(cxt != null){
			if(cxt.getBean(znxServiceStr) != null){
                footZnxService = (FootZnxService) cxt.getBean(znxServiceStr);
			}
			if(cxt.getBean(teamServiceStr) != null){
                footTeamService = (FootTeamService) cxt.getBean(teamServiceStr);
			}
			if(cxt.getBean(sjServiceStr) != null){
                footSjService = (FootSjService) cxt.getBean(sjServiceStr);
			}
            if(cxt.getBean(missionServiceStr) != null){
                footMissionService = (FootMissionService) cxt.getBean(missionServiceStr);
            }
            if(cxt.getBean(bfServiceStr) != null){
                footBfinfoService = (FootBfinfoService) cxt.getBean(bfServiceStr);
            }
            if(cxt.getBean(sociatyServiceStr) != null){
			    footSociatyInfoService = (FootSociatyInfoService) cxt.getBean(sociatyServiceStr);
            }
		}
	}

	/**
	 * 处理站内信
	 * @param request 参数
	 */
	private void processData(HttpServletRequest request){
        HttpSession session = request.getSession(true);
        FootUser user = (FootUser)session.getAttribute(Constants.USER);
        //处理收件箱
        if(user != null){
            //获取站内信放入session中
			FootZnxSearchForm footZnxSearchForm = new FootZnxSearchForm();
			footZnxSearchForm.setResiver(user.getId());
			footZnxSearchForm.setReaded(false);
            List<FootZnx> znxList = footZnxService.findall(footZnxSearchForm);
            if(znxList != null && !znxList.isEmpty()){
                session.setAttribute("znxList", znxList);
                session.setAttribute("znxSize", znxList.size());
            }else{
                session.setAttribute("znxList", null);
                session.setAttribute("znxSize", 0);
            }

            //获取当前用户footteam常规赛信息及财政信息
            FootTeam team = footTeamService.getTeamByUserid(user.getId());
            if(team != null){
                session.setAttribute("myTeam", team);
            }else{
                session.setAttribute("myTeam", null);
            }

            FootSociatyInfo info = footSociatyInfoService.getSociatyByUserId(user.getId());
            if(info != null){
                session.setAttribute("mySociaty", info);
            }else{
                session.setAttribute("mySociaty", null);
            }

            FootSj sj = footSjService.get(footSjService.getSj());
            FootMission mission1 = footMissionService.findMissionByUserIdandStatus(user.getId(), sj.getSjzt());
            FootMission mission2 = footMissionService.findMissionByUserIdandStatus(user.getId(), null);
            List<FootMission> missionlist = new ArrayList<>();
            if(null != mission1 && null != mission2){
                missionlist.add(mission1);
                missionlist.add(mission2);
                session.setAttribute("missions", missionlist);
            }else{
                session.setAttribute("missions", null);
            }
            List<Integer> intlist = new ArrayList<>();
            //查找对应任务的完成数量
            intlist.add(footBfinfoService.countMissionNumByUserId(user.getId(), 1));
            intlist.add(footBfinfoService.countMissionNumByUserId(user.getId(), 2));
            session.setAttribute("num", intlist);
        }
	}

	/**
	 * 结束拦截
	 * @param request 参数
	 * @param response 参数
	 * @param handler 参数
	 * @param ex 参数
	 * @throws Exception 异常
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		//System.out.println(">>>MyInterceptor>>>>>>>在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）")
	}

}
